package com.dycong.common.IO.nio;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.EnumSet;

import static java.nio.file.LinkOption.NOFOLLOW_LINKS;

/**
 * Created by dycong on 2017/3/27.
 * TODO Path to Path 是指package java.nio.file下的Files提供放入copy()方法
 * TODO copy()速度似乎是Path to Path-->FileChannel.transferTo()-->FileChannel buffer模式/FileChannel map模式-->各种IO/Channel
 */
public class TestFileCopy {
    private final static Path copy_from = Paths.get("D:/电影珍藏/[电影天堂www.dygod.cn]初恋50次BD中英双字.rmvb");
    private final static Path copy_to = Paths.get("D:/[电影天堂www.dygod.cn]初恋50次BD中英双字.rmvb");
    private static long startTime, elapsedTime;
    private static int bufferSizeKB = 4;//also tested for 16, 32, 64, 128, 256 and 1024
    private static int bufferSize = bufferSizeKB * 1024;


    public static void main(String[] args) throws Exception {

        transferfrom();

        transferTo();

        nonDirectBuffer();

        directBuffer();

        mapperedBuffer();

        ioBufferedStream();

        ioUnBufferedStream();

        copyPath2Path();

        copyInputStream2Path();

        copyPath2OutputStream();

        //randomReadFile();

    }


    public static void transferfrom() {

        try (FileChannel fileChannel_from = (FileChannel.open(copy_from,
                EnumSet.of(StandardOpenOption.READ)));
             FileChannel fileChannel_to = (FileChannel.open(copy_to,
                     EnumSet.of(StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE)))) {

            startTime = System.nanoTime();
            fileChannel_to.transferFrom(fileChannel_from, 0L, (int) fileChannel_from.size());
            elapsedTime = System.nanoTime() - startTime;
            System.out.println("Elapsed Time is " + (elapsedTime / 1000000000.0) + " seconds");
        } catch (IOException ex) {
            System.err.println(ex);
        }
        deleteCopied(copy_to);
    }

    public static void transferTo() throws Exception {
        try (FileChannel fileChannel_from = (FileChannel.open(copy_from,
                EnumSet.of(StandardOpenOption.READ)));
             FileChannel fileChannel_to = (FileChannel.open(copy_to,
                     EnumSet.of(StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE)))) {

            startTime = System.nanoTime();

            fileChannel_from.transferTo(0L, fileChannel_from.size(), fileChannel_to);

            elapsedTime = System.nanoTime() - startTime;
            System.out.println("Elapsed Time is " + (elapsedTime / 1000000000.0) + " seconds");
        } catch (IOException ex) {
            System.err.println(ex);
        }
        deleteCopied(copy_to);

    }

    public static void nonDirectBuffer() {

        try (
                FileChannel fileChannel_from = FileChannel.open(copy_from,
                        EnumSet.of(StandardOpenOption.READ));
                FileChannel fileChannel_to = FileChannel.open(copy_to,
                        EnumSet.of(StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE));) {

            startTime = System.nanoTime();
            ByteBuffer bytebuffer = ByteBuffer.allocate(bufferSize);
            int bytesCount;
            while ((bytesCount = fileChannel_from.read(bytebuffer)) > 0) {
                bytebuffer.flip();
                fileChannel_to.write(bytebuffer);
                bytebuffer.clear();
            }

            elapsedTime = System.nanoTime() - startTime;
            System.out.println("Elapsed Time is " + (elapsedTime / 1000000000.0) + " seconds");
        } catch (IOException ex) {
            System.err.println(ex);
        }
        deleteCopied(copy_to);
    }

    public static void directBuffer() {
        try (
                FileChannel fileChannel_to = FileChannel.open(copy_to,
                        EnumSet.of(StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE));
                FileChannel fileChannel_from = (FileChannel.open(copy_from,
                        EnumSet.of(StandardOpenOption.READ)));) {

            startTime = System.nanoTime();
            ByteBuffer bytebuffer = ByteBuffer.allocateDirect(bufferSize);
            int bytesCount;
            while ((bytesCount = fileChannel_from.read(bytebuffer)) > 0) {
                bytebuffer.flip();
                fileChannel_to.write(bytebuffer);
                bytebuffer.clear();
            }

            elapsedTime = System.nanoTime() - startTime;
            System.out.println("Elapsed Time is " + (elapsedTime / 1000000000.0) + " seconds");
        } catch (IOException ex) {
            System.err.println(ex);
        }

        deleteCopied(copy_to);
    }


    public static void mapperedBuffer() throws Exception {
        //todo 删除已有的文件
        Files.deleteIfExists(copy_to);
//        copy_to.toFile().delete();
//        new File(copy_to.toUri()).delete();
        try (FileChannel fileChannel_from = (FileChannel.open(copy_from,
                EnumSet.of(StandardOpenOption.READ)));
             FileChannel fileChannel_to = (FileChannel.open(copy_to,
                     EnumSet.of(StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE, StandardOpenOption.READ)))) {

            startTime = System.nanoTime();
            int i = 0;
            long size = fileChannel_from.size() / 30;
            ByteBuffer rr, ww = null;
            while ((i < fileChannel_from.size()) && (fileChannel_from.size() - i) > size) {
                //TODO map()返回的MappedByteBuffer capacity为返回时的固定值，limit=capacity,position为0
                rr = fileChannel_from.map(FileChannel.MapMode.READ_ONLY, i, size);
                ww = fileChannel_to.map(FileChannel.MapMode.READ_WRITE, i, size);
                ww.put(rr);
                rr.clear();
                ww.clear();
                i += size;
            }
//// TODO: 2017/3/27 为了预防超出文件边界导致异常，position+size超出边界之后会有异常抛出
            rr = fileChannel_from.map(FileChannel.MapMode.READ_ONLY, i, fileChannel_from.size() - i + 100);
            ww = fileChannel_to.map(FileChannel.MapMode.READ_WRITE, i, fileChannel_from.size() - i);
            ww.put(rr);
            rr.clear();
            ww.clear();
            elapsedTime = System.nanoTime() - startTime;
            System.out.println("Elapsed Time is " + (elapsedTime / 1000000000.0) + " seconds");

        } catch (IOException ex) {
            System.err.println(ex);
        }

        deleteCopied(copy_to);

    }


    public static void ioBufferedStream() {

        File inFileStr = copy_from.toFile();
        File outFileStr = copy_to.toFile();
        try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(inFileStr));
             BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(outFileStr))) {
            startTime = System.nanoTime();
            byte[] byteArray = new byte[bufferSize];
            int bytesCount;
            while ((bytesCount = in.read(byteArray)) != -1) {
                out.write(byteArray, 0, bytesCount);
            }
            elapsedTime = System.nanoTime() - startTime;
            System.out.println("Elapsed Time is " + (elapsedTime / 1000000000.0) + " seconds");
        } catch (IOException ex) {
            System.err.println(ex);
        }
        deleteCopied(copy_to);
    }


    public static void ioUnBufferedStream() {

        File inFileStr = copy_from.toFile();
        File outFileStr = copy_to.toFile();
        try (FileInputStream in = new FileInputStream(inFileStr);
             FileOutputStream out = new FileOutputStream(outFileStr)) {
            startTime = System.nanoTime();
            byte[] byteArray = new byte[bufferSize];
            int bytesCount;
            while ((bytesCount = in.read(byteArray)) != -1) {
                out.write(byteArray, 0, bytesCount);
            }

            elapsedTime = System.nanoTime() - startTime;
            System.out.println("Elapsed Time is " + (elapsedTime / 1000000000.0) + " seconds");
        } catch (IOException ex) {
            System.err.println(ex);
        }
        deleteCopied(copy_to);
    }

    //todo Path to Path???最快方式
    //todo 三种 Files.copy() 方法
    public static void copyPath2Path() {
        try {
            startTime = System.nanoTime();
            Files.copy(copy_from, copy_to, NOFOLLOW_LINKS);
            elapsedTime = System.nanoTime() - startTime;
            System.out.println("Elapsed Time is " + (elapsedTime / 1000000000.0) + " seconds");
        } catch (IOException e) {
            System.err.println(e);
        }
        deleteCopied(copy_to);
    }


    public static void copyInputStream2Path() {
        try (InputStream is = new FileInputStream(copy_from.toFile())) {
            startTime = System.nanoTime();
            Files.copy(is, copy_to);
            elapsedTime = System.nanoTime() - startTime;
            System.out.println("Elapsed Time is " + (elapsedTime / 1000000000.0) + " seconds");
        } catch (IOException e) {
            System.err.println(e);
        }
        deleteCopied(copy_to);
    }


    public static void copyPath2OutputStream() {
        try (OutputStream os = new FileOutputStream(copy_to.toFile())) {
            startTime = System.nanoTime();
            Files.copy(copy_from, os);
            elapsedTime = System.nanoTime() - startTime;
            System.out.println("Elapsed Time is " + (elapsedTime / 1000000000.0) + " seconds");
        } catch (IOException e) {
            System.err.println(e);
        }
    }


    public static void randomReadFile() {
        try (
                RandomAccessFile read = new RandomAccessFile("C:\\Users\\asus\\Desktop\\cn_windows_7_ultimate_with_sp1_x86_dvd_618763.iso", "r");
                RandomAccessFile writer = new RandomAccessFile("C:\\Users\\asus\\Desktop\\dwTest\\cn_windows_7_ultimate_with_sp1_x86_dvd_618763.iso", "rw");) {
            startTime = System.nanoTime();
            byte[] b = new byte[200 * 1024 * 1024];
            while (read.read(b) != -1) {
                writer.write(b);
            }
            elapsedTime = System.nanoTime() - startTime;
            System.out.println("Elapsed Time is " + (elapsedTime / 1000000000.0) + " seconds");

        } catch (Exception e) {
            System.err.println(e);
        }
        deleteCopied(copy_to);
    }

    public static void deleteCopied(Path path) {
        try {
            Files.deleteIfExists(path);
        } catch (IOException ex) {
            System.err.println(ex);
        }

    }
}
